package com.roy.minimq.remoting.domain.nettyserver;

import com.roy.minimq.remoting.domain.entity.RemotingCommand;
import io.netty.channel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ：楼兰
 * @date ：Created in 2021/8/9
 * @description:
 **/
@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<RemotingCommand> {
    private Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);

    private NettyRemotingServer remotingServer;

    public NettyServerHandler(NettyRemotingServer remotingServer) {
        this.remotingServer = remotingServer;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RemotingCommand remotingCommand) throws Exception {
        logger.info("received command " + remotingCommand);

        //服务端的测试逻辑 直接返回结果。
//        String response = "response from server";
//        remotingCommand.setMessage(response);
//        final ChannelFuture future = ctx.writeAndFlush(remotingCommand);
//        future.addListener(new ChannelFutureListener() {
//            @Override
//            public void operationComplete(ChannelFuture channelFuture) throws Exception {
//                if (future.isDone()) {
//                    logger.info("response to client: {}",remotingCommand);
//                }
//            }
//        });

        remotingServer.processRequest(ctx,remotingCommand);
    }

//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        logger.error("server handler exceptionCaught : {} ", cause);
//        ctx.close();
//    }
}
